﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using WindowsInput.Native;
namespace Tornado
{
    public class WinProcess
    {
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();
        [DllImport("user32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32")]
        public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
        [DllImport("user32.dll")]
        public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        const uint WM_KEYDOWN = 0x100;
        const uint WM_SYSCOMMAND = 0x018;
        const uint SC_CLOSE = 0x053;

        public static string powerPointString = "POWERPNT";
        public static string magnifierProcess = "Magnify";

        //This way is not right for powerpoint, read more : http://support.microsoft.com/kb/308825
        public static void ControlSlide_oild(VirtualKeyCode keyCode)
        {
            Process[] powerpointProcess = Process.GetProcessesByName(powerPointString);
            if (powerpointProcess.Length != 0)
            {
                SendMessage(powerpointProcess[0].MainWindowHandle, WM_KEYDOWN, ((IntPtr)keyCode), (IntPtr)0);
            }
        }

        public static bool isMagnifyRunning()
        {
            return Process.GetProcessesByName(magnifierProcess).Length != 0;
        }

        public static bool isPowerpointRunning()
        {
            return Process.GetProcessesByName(powerPointString).Length != 0;
        }

        public static bool forcePowerpoint()
        {
            Process[] powerpointProcess = Process.GetProcessesByName(powerPointString);
            if (powerpointProcess.Length == 0)
            {
                return false;
            }
            if (!IsWindowActive(powerpointProcess[0]))
            {
                SetForegroundWindow(powerpointProcess[0].MainWindowHandle);
            }
            return true;
        }
        public static bool IsWindowActive(Process proc)
        {
            if(proc != null)
            {
                proc.Refresh();
                return proc.MainWindowHandle.Equals(GetForegroundWindow());
            }
            return false;
        }
        public static bool isOpenFile()
        {
            Process[] powerpointProcess = Process.GetProcessesByName(powerPointString);
            if (powerpointProcess.Length == 0)
                return false;
            return powerpointProcess[0].MainWindowTitle.TrimEnd("PowerPoint".ToCharArray()).Length != 0;
        }
    }
}
